package com.longrise.android.byjk.plugins.dealsituation.course.video2.education.insurance;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.WindowManager;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.common.base.BaseActivity;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.plugins.course.coursedetail.courseadapter.CourseDetailAdapter;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.dialog.CatalogDialog;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.dialog.CurrencyDialog;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.dialog.HasqaDialog;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.dialog.UploadDialog;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.education.insurance.videocontroller.VideoController;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.media.IjkVideoView;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.ToDispatchStudy;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.VideoConsts;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.VideoParams;
import com.longrise.android.byjk.utils.FileUtil;
import com.longrise.common.utils.PrintLog;
import com.longrise.android.upload_offline.DBDAO;


/**
 * Created by godliness on 2017/8/22.
 * 保险课件学习
 */

public class InsuranceActivity extends BaseActivity<InsurancePresenter> implements InsuranceView, CourseDetailAdapter.OnChildItemClickListener, VideoController.OnProgressInterface, HasqaDialog.OnHasqaListener, UploadDialog.DialogUploadInterface {

    private static final String TAG = "InsuranceActivity";

    private IjkVideoView mPlayer;
    private VideoController mVideoController;

    private VideoParams mParams;
    private String mVideoPath;

    private CatalogDialog mCatalogDialog;
    private HasqaDialog mHasqaDialog;
    private UploadDialog mUploadDialog;
    private CurrencyDialog mCurrencyDialog;

    /**
     * 保存当前Activity的状态 onResume() 或者 onPause()
     */
    private boolean mResume = true;
    /**
     * 播放器是否初始化完成
     */
    private boolean mPrepared;
    /**
     * 当前播放是否出错了
     */
    private boolean mError;
    /**
     * Activity不可见时，保存播放器状态，暂停or播放
     */
    private boolean mPauseBeforeState;

    /**
     * 是否播放完成
     */
    private boolean mCompleted;

    @Override
    public int getContentViewId(@Nullable Bundle state) {
        if (state != null) {
            onRestoreState(state);
        } else {
            getExtraData();
        }
        return R.layout.activity_insurancevideo;
    }

    @Override
    public void beforeSetContentView() {
        initTheme();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    @Override
    public void initView() {
        mPlayer = (IjkVideoView) findViewById(R.id.video_insuranceact);
        mVideoController = new VideoController();
        mVideoController.addVideoController(mPlayer);
        regEvent(true);
        toRequestVideo();
    }

    private void toRequestVideo() {
        mPresenter.toRequest(mParams);
    }

    private void regEvent(boolean isClick) {
        if (mVideoController != null) {
            mVideoController.addProgressListener(isClick ? this : null);
        }
    }

    private void getExtraData() {
        Intent extraIntent = getIntent();
        mParams = extraIntent.getParcelableExtra(VideoConsts.VIDEO_PARAMS_PARCELABLE);
        setVideoTitle();
    }

    private void startPlayer(String videoPath) {
        if (mVideoController == null || mParams == null) {
            return;
        }
        mVideoController.setVideoURI(mPresenter.mResumePos, checkPath(videoPath));
        mVideoController.setProgressEnable(mParams.mFinish || mParams.mVideopass);
        mVideoPath = videoPath;
        setVideoTitle();
    }

    private Uri checkPath(String vsource) {
        return Uri.parse(videoLocation(vsource));
    }

    /**
     * 检查视频课件是否已缓存在本地
     */
    private String videoLocation(String vsource) {
        boolean isLocal = FileUtil.isHasDownloaded(this, UserInfor.getInstance().getUserid(), mParams.mCwid);
        if (!isLocal) {
            return vsource;
        }
        EntityBean bean = DBDAO.getInstance().getLocalVideoCachePath(mParams.mCourseId, mParams.mCwid);
        if (bean == null) {
            return vsource;
        }
        String cachepath = bean.getString("cachepath", "");
        PrintLog.e(TAG, "cachepath: " + cachepath);
        return strIsEmpty(cachepath) ? vsource : cachepath;
    }

    private void setVideoTitle() {
        if (mParams != null && mVideoController != null) {
            String title = mParams.mCwidName + (mParams.mHasqa ? "（课后习题）" : "");
            mVideoController.setTitle(title);
        }
    }

    /**
     * 目录
     */
    private void createCatalogDialog() {
        if (mParams == null) {
            return;
        }
        dismissCataLogDialog();
        mCatalogDialog = new CatalogDialog(this);
        mCatalogDialog.setParams(mParams.mCourseId, mParams.mCwid);
        mCatalogDialog.setOnItemClick(this);
        mCatalogDialog.show();
        hideVideoController();
    }

    /**
     * 课后习题
     */
    private void createHasqaDialog() {
        if (mParams == null) {
            return;
        }
        dismissHasqaDialog();
        mHasqaDialog = new HasqaDialog(this);
        mHasqaDialog.setFlag(mParams.mFinish);
        mHasqaDialog.setQaListener(this);
        mHasqaDialog.show();
    }

    /**
     * 维护过程
     */
    private void createUploadDialog(int errorType) {
        dismissUploadDialog();
        mUploadDialog = new UploadDialog(this, errorType);
        mUploadDialog.setUploadInterface(this);
        mUploadDialog.show();
    }

    /**
     * 学历教育课件通过之后弹窗提示
     */
    private void createCurrencyDialog() {
        dismissCurrencyDialog();
        mCurrencyDialog = new CurrencyDialog(this);
        mCurrencyDialog.show();
    }

    private void dismissHasqaDialog() {
        if (mHasqaDialog != null && mHasqaDialog.isShowing()) {
            mHasqaDialog.dismiss();
            mHasqaDialog = null;
        }
    }

    private void dismissCataLogDialog() {
        if (mCatalogDialog != null && mCatalogDialog.isShowing()) {
            mCatalogDialog.dismiss();
            mCatalogDialog = null;
        }
    }

    private void dismissUploadDialog() {
        if (mUploadDialog != null && mUploadDialog.isShowing()) {
            mUploadDialog.dismiss();
            mUploadDialog = null;
        }
    }

    private void dismissCurrencyDialog() {
        if (mCurrencyDialog != null && mCurrencyDialog.isShowing()) {
            mCurrencyDialog.dismiss();
            mCurrencyDialog = null;
        }
    }

    private void hideVideoController() {
        if (mVideoController != null) {
            mVideoController.hide();
        }
    }

    private boolean strIsEmpty(String pars) {
        return TextUtils.isEmpty(pars);
    }

    @Override
    protected void onResume() {
        super.onResume();
        doResume();
    }

    private void doResume() {
        mResume = true;
        if (mPauseBeforeState && mPrepared) {
            mVideoController.start();
        }
        if (!mPauseBeforeState && mPrepared && !mError) {
            mVideoController.show();
        }
        mPresenter.startDefendStudy();
    }

    @Override
    protected void onPause() {
        super.onPause();
        doPause();
    }

    private void doPause() {
        mResume = false;
        if (!mPrepared) {
            mPauseBeforeState = true;
        } else {
            mPauseBeforeState = mVideoController.isPlaying();
        }
        mVideoController.pause();
        mPresenter.stopDefendStudy();
    }

    /**
     * @param videopath url地址
     */
    @Override
    public void parseVideoInfor(String videopath) {
        if (isFinishing()) {
            return;
        }
        startPlayer(videopath);
    }

    private void onRestoreState(Bundle state) {
        if (state != null) {
            mParams = state.getParcelable(VideoConsts.VIDEO_PARAMS_PARCELABLE);
        }
    }

    private void initState() {
        mPrepared = false;
        mVideoPath = null;
    }

    private void initPrepared() {
        mPrepared = true;
        mError = false;
        mCompleted = false;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable(VideoConsts.VIDEO_PARAMS_PARCELABLE, mParams);
    }

    @Override
    public void onItemClick(VideoParams params) {
        if (ToDispatchStudy.VIDEO.equals(params.mCwidStyle)) {
            mPresenter.stopDefendStudy();
            initState();
            mParams = params;
            toRequestVideo();
            return;
        }
        //学历教育课件
        mPresenter.toStudyStart(params);
    }

    @Override
    public void onBack() {
        finish();
    }

    /**
     * 课后习题
     */
    @Override
    public void hasqa() {
        createHasqaDialog();
    }

    /**
     * 课件是否初始化完成
     */
    @Override
    public boolean isPrepared() {
        return mPrepared;
    }

    /**
     * 维护过程出错
     *
     * @param errorType
     */
    @Override
    public void defendError(int errorType) {
        if (isFinishing()) {
            return;
        }
        if (mVideoController != null) {
            mVideoController.pause();
        }
        createUploadDialog(errorType);
    }

    /**
     * 该课件已通过
     */
    @Override
    public void defendSuccess() {
        if (isFinishing()) {
            return;
        }
        if (mVideoController != null) {
            mVideoController.setProgressEnable(true);
        }
        if (mCompleted) {
            completeOptions();
        }

        otherOption();
    }

    /**
     * 学历教育课件 【特殊处理】
     */
    private void otherOption() {
        if (mParams != null && !isFinishing()) {
            int groupType = mParams.mGroupType;
            if (groupType == 19) {  //19固定值，学历教育课件类型
                if (!mParams.mVideopass) {
                    createCurrencyDialog();
                }
            }
        }
    }

    @Override
    public int getCurrentPosition() {
        return mPlayer == null ? 0 : mPlayer.getCurrentPosition();
    }

    @Override
    public int getDuration() {
        return mPlayer == null ? 0 : mPlayer.getDuration();
    }

    /**
     * 目录
     */
    @Override
    public void onRecord() {
        createCatalogDialog();
    }

    /**
     * 播放完成
     */
    @Override
    public void onComplete() {
        completeOptions();
        PrintLog.e(TAG, "播放完成");
    }

    /**
     * 视频播放过程中出错
     */
    @Override
    public void onVideoError() {
        mError = true;
        if (mVideoController != null) {
            mVideoController.exception(true, "播放出错了，请稍后再试...");
        }
    }

    /**
     * 初始化完成
     */
    @Override
    public boolean onPrepared() {
        initPrepared();
        mPresenter.monitorDefendStudy(getDuration());
        return mResume;
    }

    /**
     * 点击重试
     */
    @Override
    public void onReset() {
        if (!checkNetWorkEnable()) {
            return;
        }
        if (mVideoController != null) {
            mVideoController.buffering(true);
        }
        if (!strIsEmpty(mVideoPath)) {
            startPlayer(mVideoPath);
            return;
        }
        toRequestVideo();
    }

    /**
     * 接口请求出错
     */
    @Override
    public void onError() {
        dismissLoadingDialog();
        if (mVideoController != null) {
            mVideoController.exception(true, "请求出错了，请稍后再试...");
        }
        mVideoPath = null;
        mError = true;
    }

    @Override
    public void showToast(String msg) {
        super.showToast(msg);
    }

    @Override
    public void showLoadingDialog() {
        if (mVideoController != null) {
            mVideoController.setHaze(true, false);
        }
        if (mVideoController != null) {
            mVideoController.buffering(true);
        }
    }

    @Override
    public void dismissLoadingDialog() {
        if (mVideoController != null) {
            mVideoController.buffering(false);
        }
    }

    /**
     * 课后习题
     */
    @Override
    public void toQa() {
        mPresenter.toQa();
    }

    /**
     * 同步记录  手动同步
     */
    @Override
    public void onUpload() {
        mPresenter.preformStart();
    }

    /**
     * UploadDialog back
     */
    @Override
    public void back() {
        finish();
    }

    /**
     * 播放完成逻辑
     */
    private void completeOptions() {
        mCompleted = true;
        mPresenter.stopDefendStudy();
        if (mParams == null) {
            return;
        }
        boolean videopass = mParams.mVideopass;
        if (!videopass) {
            createUploadDialog(UploadDialog.DIALOG_TYPE_ONE);
            return;
        }
        mPresenter.exerciseOptions(mParams);
        cwidHasqaMessage();

    }

    /**
     * 播放完成，界面提示语
     */
    private void cwidHasqaMessage() {
        if (mParams == null) {
            return;
        }
        boolean hasqa = mParams.mHasqa;
        if (mVideoController != null) {
            mVideoController.complete(hasqa ? getString(mParams.mFinish ? R.string.video_paly_finish : R.string.video_play_finish_test) : getString(R.string.video_paly_finish));
        }
    }

    private void release() {
        mPresenter.setFinished();
        mVideoController.release();
        regEvent(false);
        dismissCataLogDialog();
        dismissHasqaDialog();
        mPresenter.sendMessage();
        mPlayer = null;
    }

    @Override
    protected void onStop() {
        super.onStop();
        dismissCataLogDialog();
    }

    @Override
    protected void onDestroy() {
        release();
        super.onDestroy();
    }
}
